package router

import (
	"net/http"
	"xiaomi_demo/controllers"
	"xiaomi_demo/middieware"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func Router() *gin.Engine {
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()

	store := cookie.NewStore([]byte("something-very-secret"))
	//  初始化cookie会话存储
	r.Use(sessions.Sessions("mysession", store))

	// 加载文件
	r.Static("/css", "static/css")
	r.Static("/font", "static/font")
	r.LoadHTMLGlob("static/*.html")

	r.NoRoute(func(ctx *gin.Context) {
		ctx.HTML(http.StatusNotFound, "404.html", nil)
	})
	errorInfo := controllers.ErrorInfo{}
	r.GET("/index", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "index.html", gin.H{
			"Message": "jaingxiaonian",
		})
	})

	r.GET("/register", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "register.html", errorInfo)
	})

	r.GET("/login", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "login.html", errorInfo)
	})

	r.GET("/logins", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "logins.html", errorInfo)
	})

	r.POST("/register", controllers.UserController{}.Register)

	r.POST("/login", controllers.UserController{}.Login)
	r.POST("/logins", controllers.UserController{}.Login)

	authed := r.Group("/")
	authed.Use(middieware.JWT())
	{
		authed.GET("jwt", func(ctx *gin.Context) {
			ctx.HTML(http.StatusOK, "jwt.html", errorInfo)
		})
	}

	return r
}
